<?php

namespace Common\Model;

use Think\Model;

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------
class MemberModel extends Model {



    /**
     * 用户登录
     * @author 462193409@qq.com
     */
    public function login($username, $password) {
        //去除前后空格
        $username = trim($username);
        $map['truename'] = array('eq', $username); //用户名登陆
        $user = $this->where($map)->find(); //查找用户
        if (!$user) {
            $ajax = array('status' => 0, 'info' => '用户不存在或被禁用!');
            echo json_encode($ajax);
            return;
        } else {
            if ($user['status'] == 1) {
                list($password, $salt) = password($password, $user['salt']);
                if ($password != $user['password']) {
                    $ajax = array('status' => 0, 'info' => '密码不正确!');
                } else {
                    //更新登录信息
                    $data = array(
                        'id' =>$user['id'],
                        'login_num' => array('exp', '`login_num`+1'),
                        'last_login_time' => time(),
                        'last_login_ip' => get_client_ip(1),
                    );
                    $this->save($data);
                    
                    $this->autoLogin($user);
                    return $user['truename'];
                }
            } else {
                $ajax = array('status' => 0, 'info' => '您不能登录，因为账号异常!');
            }
            echo json_encode($ajax);
            return;
        }
    }

    /**
     * 设置登录状态
     * @author 462193409@qq.com
     */
    public function autoLogin($user) {
        //记录登录SESSION和COOKIES
        session('manager_id', $user['id']);
        session('manager_auth', $user);
    }

}
